<template>
  <div class="app-container">
    <div id="printBox">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 394px; height: 394px"
        >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <canvas :id="`barcode_${item?.id || ''}`"></canvas> -->
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 390px;
            "
          >
            <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
              ><text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.produceTransferFormCode || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >存货编码：&nbsp;<text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >材质：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.materialQuality || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >规格型号：&nbsp;<text
                style="font-size: 20px; font-weight: 600"
                >{{ item?.materialSpecification || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >图号：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 390px">
            <br /><span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 10px;
                font-weight: 600;
              "
              >生产批次：<text
                style="font-size: 20px; font-weight: 600; margin-right: 10px"
                >{{ item?.remarks || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：&nbsp;<text style="font-size: 20px; font-weight: 600"
                >{{ item?.productQuantity || "" }}
                {{ item?.unitName || "" }}</text
              >
            </span>
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 12px; width: 390px; margin-bottom: 1px">
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印时间：&nbsp;<text>{{ item?.printTime || "" }}</text></span
            >
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：&nbsp;<text
                >{{ route.query.printername }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 14px; width: 400px; display: flex">
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者1：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
        <div style="margin-top: 10px">
          <div style="text-align: center" v-show="printData.length > 0">
            <el-button size="small" @click="getPrintData()">打印条码</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { getLodop } from "@/utils/LodopFuncs";
import { RootObject } from "./index";
import { useRoute, useRouter } from "vue-router";
import JsBarcode from "jsbarcode";
import QRCode from "qrcode";
import defaultSettings from "@/settings";
// import { uni } from "@/utils/uni.webview.1.5.4.js";
// 1、name每个页面不能重复，2、路由在router.ts中添加，3、添加至路由白名单（permission.ts中whiteList）
defineOptions({
  name: "IframePrint",
  inheritAttrs: false,
});

// 打印模板全用div和span等原生html书写（确保打印格式不变）
// 样式全用行内style书写（确保样式生效）

const route = useRoute();

// 打印数据，数组形式
const printData = ref<RootObject[]>([]);

let router = useRouter();

// 监听路由变化，检测是否开始打印
watch(
  () => router.currentRoute.value,
  (newValue) => {
    console.log("watch", JSON.stringify(newValue));
    if (newValue.query?.id && newValue.query?.printer) {
      getPrintData();
    }
  },
  { immediate: true, deep: true }
);

// 定义二维码options
let barOptions = {
  fontSize: 14,
  height: 50,
  fontOptions: "bold",
  textAlign: "center",
  margin: 0,
  width: 2,
  font: "Microsoft YaHei",
  displayValue: false, //是否在条形码下方显示文字
};

// 获取打印数据
async function getPrintData() {
  const { data } = await request({
    url: `/mes/mesproducetransferform/print/${route.query.id}`,
    method: "get",
    data: {},
  })
    .finally(() => {})
    .catch((e) => {
      uni.postMessage({
        data: {
          message: "打印失败" + e,
          code: 0,
          id: route.query.id,
          printer: route.query.printer,
        },
      });
    });
  // printData.value = [data, data, data]; //多张打印
  printData.value = [data]; //单张打印
  nextTick(() => {
    printData.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);
      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(
            qrCodeElement,
            e.produceTransferFormCode || "",
            {
              width: 100, // 可以根据需要调整二维码的大小
              margin: 1, // 可以根据需要调整二维码的边距
            }
          );
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`工序流转单打印-${route.query.id}`);
    // LODOP.SET_LICENSES(
    //   defaultSettings.printCompany,
    //   defaultSettings.printLicenses,
    //   "",
    //   ""
    // );
    printData.value?.map((e) => {
      printFun(e, LODOP);
    });
    LODOP.SET_PRINTER_INDEX(route.query.printer);
    LODOP.PRINT(); // 打印
    //LODOP.PREVIEW(); // 预览
    if (uni) {
      uni.postMessage({
        data: {
          message: "已成功进入打印队列，请稍后",
          code: 200,
          id: route.query.id,
          printer: route.query.printer,
        },
      });
    }
    // 打印结束调用
    insertOperateLog(route.query.id, route.query.printer);
  }, 500);
}

function printFun(pitem: RootObject, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  //LODOP.ADD_PRINT_RECT(0, 5, 310, 220, 0, 1); //边框设置：上、左、宽、高、线条：0实线 1虚线
  //LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  //LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    "40mm",
    "10mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "5mm",
    "30mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.produceTransferFormCode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}
//打印日志信息
const operateLog = ref({
  logLevel: "INFO",
  applicationName: "jcfk-mes",
  modular: "报工结束",
  businessType: "打印",
  info: "",
});
//结束打印
async function insertOperateLog(id: any, name: any) {
  operateLog.value.info = id + "," + name;
  await request({
    method: "POST",
    url: "/system/sysOperateLog/insert",
    data: operateLog.value,
  }).catch((e) => {});
}

onMounted(async () => {
  // 数据字典表获取
  // await useDictStore.getDictionaryList();
  // 获取打印数据
  // getPrintData();
});
</script>

<style lang="scss" scoped>
.app-container {
  height: inherit;
  overflow: scroll;
}
</style>
